﻿using System;
using System.Collections.Generic;
using NServiceBus.Management.Messages.Statistics;
using NServiceBus.Unicast.Transport;

namespace NServiceBus.Management.Managers.Impl
{
    public class StatisticsManager : ManagerBase,
                                             IStatisticsManager
    {
        //private readonly MessageStatistics messageStatistics = new MessageStatistics();
        private readonly IDictionary<Type, int> messagesReceived = new Dictionary<Type, int>();

        public StatisticsManager()
        {
            startTime = DateTime.Now;
        }

        public override ITransport Transport
        {
            get
            {
                return base.Transport;
            }
            set
            {
                base.Transport = value;

                //subscribe for transport events
                base.Transport.TransportMessageReceived += HandleTransportMessageReceived;

            }
        }

        public void UpdateStatisticsFor(IMessage message)
        {
            lock (messagesReceived)
            {
                int count;
                messagesReceived.TryGetValue(message.GetType(), out count);
                messagesReceived[message.GetType()] = count + 1;
            }
        }

        private void HandleTransportMessageReceived(object sender, TransportMessageReceivedEventArgs eventArgs)
        {
            foreach (IMessage message in eventArgs.Message.Body)
            {
                UpdateStatisticsFor(message);
            }
        }

        private DateTime startTime;
        public void SendEndpointStatistics()
        {
            lock (messagesReceived)
            {
                var message = new StatisticsMessage { Start = startTime, End = DateTime.Now, NumberOfMessagesReceived = new Dictionary<Type, int>(messagesReceived) };

                startTime = message.End;


                Bus.Send(message);

                messagesReceived.Clear();
            }
        }


        public IDictionary<Type, int> NumberOfMessagesReceived
        {
            get
            {
                return messagesReceived;
            }
            
        }
    }
}
